package iosr11.ui.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class GradeValidator implements Validator {
	
	private static final String errorDetail = "Ocena musi byc stopniem zgodnym z regulaminem AGH.";
	private static final String	error = "Bledna ocena.";
	
	private static double[] GRADES = {2.0, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0};
	
	@Override
	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
		if (value == null) return;
		
		if(!gradeCheck(value.toString())){
			FacesMessage msg = new FacesMessage();	//Messages.getMessage("iosr11.ui.common.messages", "badLogin", null);
			msg.setDetail(errorDetail);
			msg.setSummary(error);
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
	}
	
	private static boolean gradeCheck(String grade){
		String tmpGrade = grade.replace(",", ".");
		try{
			double n = Double.parseDouble(tmpGrade);
			for(double number : GRADES){
				if (n == number) return true;
			}
		}catch(NumberFormatException e){
			e.printStackTrace();
		}
		return false;
	}
}
